<template>
  <div>
      <van-cell  v-for="(text, index) in suggestionList" :key="index" @click="$emit('search', text)">
        <van-icon name="search" slot="icon" class="search-icon"/>
        <div slot="title" v-html="heightLight(text)"></div>
      </van-cell>
  </div>
</template>

<script>
// 导入请求联想关键字接口
import { getSearchSuggestion } from '@/api/search'
// 导入防抖函数工具

export default {
  data () {
    return {
      suggestionList: [], // 联想建议数据列表
      timer: null // 防抖定时器
    }
  },
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  watch: {
    searchText: {
      // 防抖优化
      handler (newVal) {
        clearTimeout(this.timer)
        this.timer = setTimeout(() => {
          this.getSugList(newVal)
        }, 500)
      },
      immediate: true
    }
  },
  methods: {
    async getSugList (q) {
      try {
        const { data } = await getSearchSuggestion(q)
        this.suggestionList = data.data.options
      } catch (err) {
        this.$toast('请求失败，请稍后再试')
      }
    },
    heightLight (text) {
      // 动态创建正则匹配模式 参数二为匹配模式
      const reg = new RegExp(this.searchText, 'gi')
      return text.replace(reg, `<span class="g-color">${this.searchText}</span>`)
    }
  }
}
</script>
<style lang="less" scoped>
.search-icon {
  position: absolute;
  left: 24px;
  top: 36px;
  font-size: 25px;
  color: #999;
}
.van-cell__title {
  margin-left: 30px;
}
/deep/.g-color {
  color: rgb(2, 252, 77);
}
</style>
